import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import './FormStyles.css'; // Shared CSS file

const RegisterPage = () => {
    const [formData, setFormData] = useState({
        username: '',
        password: '',
        email: '',
        fullName: '',
        phoneNumber: '',
        // dateOfBirth: '', // Handle date input carefully
        // address: ''
    });
    const [error, setError] = useState('');
    const [success, setSuccess] = useState('');
    const [loading, setLoading] = useState(false);
    const { register } = useAuth();
    const navigate = useNavigate();

    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setSuccess('');
        setLoading(true);
        // Basic validation (more robust validation should be added)
        if (!formData.username || !formData.password || !formData.email || !formData.fullName) {
            setError('Please fill in all required fields: Username, Password, Email, Full Name.');
            setLoading(false);
            return;
        }

        try {
            // Construct payload, ensuring all fields required by backend are present
            // even if optional in the form initially.
            const payload = {
                username: formData.username,
                password: formData.password,
                email: formData.email,
                fullName: formData.fullName,
                phoneNumber: formData.phoneNumber || null, // Send null if empty
                dateOfBirth: formData.dateOfBirth || null, // Ensure correct date format or send null
                address: formData.address || null,
            };

            const responseMessage = await register(payload);
            setSuccess(responseMessage + " You can now login.");
            // navigate('/login'); // Optional: redirect to login after a delay or on button click
        } catch (err) {
            setError(err.response?.data || 'Failed to register. Please try again.');
            console.error("Register page error:", err);
        }
        setLoading(false);
    };

    return (
        <div className="form-container">
            <h2>Register</h2>
            {error && <p className="error-message">{error}</p>}
            {success && <p className="success-message">{success}</p>}
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="username">Username*</label>
                    <input type="text" id="username" name="username" value={formData.username} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label htmlFor="password">Password*</label>
                    <input type="password" id="password" name="password" value={formData.password} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label htmlFor="email">Email*</label>
                    <input type="email" id="email" name="email" value={formData.email} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label htmlFor="fullName">Full Name*</label>
                    <input type="text" id="fullName" name="fullName" value={formData.fullName} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label htmlFor="phoneNumber">Phone Number</label>
                    <input type="tel" id="phoneNumber" name="phoneNumber" value={formData.phoneNumber} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label htmlFor="dateOfBirth">Date of Birth</label>
                    <input type="date" id="dateOfBirth" name="dateOfBirth" value={formData.dateOfBirth || ''} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label htmlFor="address">Address</label>
                    <input type="text" id="address" name="address" value={formData.address || ''} onChange={handleChange} />
                </div>
                <button type="submit" className="submit-button" disabled={loading}>
                    {loading ? 'Registering...' : 'Register'}
                </button>
            </form>
            <p className="switch-form-text">
                Already have an account? <a href="/login">Login here</a>
            </p>
        </div>
    );
};

export default RegisterPage; 